<template>
  <div class="test-record-container">
    <div class="page-header">
      <h2>测试记录</h2>
      <div class="header-actions">
        <el-radio-group v-model="recordType" class="record-type-switch">
          <el-radio-button label="exam">考试记录</el-radio-button>
          <el-radio-button label="practice">练习记录</el-radio-button>
        </el-radio-group>
        <el-input
          v-model="searchQuery"
          placeholder="搜索记录"
          :prefix-icon="Search"
          class="search-input"
          clearable
        />
      </div>
    </div>

    <div class="record-grid">
      <!-- 成绩统计卡片 -->
      <el-card class="record-card stats-card">
        <div class="card-header">
          <h3>成绩统计</h3>
        </div>
        <div class="stats-content">
          <div class="stat-item">
            <div class="stat-value">{{ stats.averageScore }}</div>
            <div class="stat-label">平均分</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.highestScore }}</div>
            <div class="stat-label">最高分</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.testCount }}</div>
            <div class="stat-label">{{ recordType === 'exam' ? '考试次数' : '练习次数' }}</div>
          </div>
        </div>
      </el-card>

      <!-- 成绩趋势图表 -->
      <el-card class="record-card chart-card">
        <div class="card-header">
          <h3>成绩趋势</h3>
          <el-radio-group v-model="timeSpan" size="small" @change="updateChart">
            <el-radio-button label="day">按日</el-radio-button>
            <el-radio-button label="month">按月</el-radio-button>
          </el-radio-group>
        </div>
        <div ref="chartRef" class="chart-container"></div>
      </el-card>

      <!-- 测试记录列表 -->
      <el-card class="record-card list-card">
        <div class="card-header">
          <h3>{{ recordType === 'exam' ? '考试记录' : '练习记录' }}</h3>
        </div>
        <el-table 
          :data="filteredRecords" 
          style="width: 100%"
          :header-cell-style="{
            background: 'rgba(107, 155, 210, 0.1)',
            color: '#4a6fa5',
            fontWeight: '600'
          }"
        >
          <el-table-column prop="testName" label="名称" min-width="180">
            <template #default="scope">
              <div class="test-name">
                <span class="test-icon">{{ getTestIcon(scope.row.type) }}</span>
                <span v-if="recordType === 'exam'">
                  {{ examPapers[scope.row.paperId]?.paperName || scope.row.paperName || `考试${scope.row.examId}` }}
                </span>
                <span v-else>
                  {{ getPracticeName(scope.row) }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="correctCount" label="正确题数" width="100" v-if="recordType === 'practice'">
            <template #default="scope">
              <span>{{ scope.row.correctCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="questionCount" label="总题数" width="100" v-if="recordType === 'practice'">
            <template #default="scope">
              <span>{{ scope.row.questionCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="得分率" width="100">
            <template #default="scope">
              <span :class="['score', getScoreClass(recordType === 'exam' ? (scope.row.userScore / scope.row.totalScore * 100) : (scope.row.correctCount / scope.row.questionCount * 100))]">
                {{ recordType === 'exam' ? Math.round(scope.row.userScore / scope.row.totalScore * 100) : Math.round(scope.row.correctCount / scope.row.questionCount * 100) }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="时间" width="180">
            <template #default="scope">
              {{ formatDate(recordType === 'exam' ? scope.row.createTime : scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="用时" width="120">
            <template #default="scope">
              {{ Math.floor(scope.row.duration / 60) + '分钟' }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { useUserStore } from '../../../store/UserStore'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const searchQuery = ref('')
const recordType = ref('exam')
const timeSpan = ref('day')
const examRecords = ref([])
const practiceRecords = ref([])
const chartRef = ref(null)
const scoreChart = ref(null)
const examPapers = ref({})
const courseMap = ref({})

const stats = computed(() => {
  const records = recordType.value === 'exam' ? examRecords.value : practiceRecords.value
  console.log('当前记录类型:', recordType.value)
  console.log('当前记录数据:', records)
  
  if (records.length === 0) {
    console.log('没有记录数据')
    return {
      averageScore: 0,
      highestScore: 0,
      testCount: 0
    }
  }

  const scores = records.map(record => {
    const score = recordType.value === 'exam' 
      ? (record.userScore / record.totalScore * 100)  // 计算百分比分数
      : (record.correctCount / record.questionCount * 100)
    console.log('计算分数:', {
      recordId: record.examId || record.id,
      userScore: record.userScore,
      totalScore: record.totalScore,
      correctCount: record.correctCount,
      questionCount: record.questionCount,
      calculatedScore: score
    })
    return score
  })
  
  console.log('所有分数:', scores)
  const averageScore = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
  const highestScore = Math.round(Math.max(...scores))
  console.log('计算结果:', {
    averageScore,
    highestScore,
    testCount: records.length
  })

  return {
    averageScore,
    highestScore,
    testCount: records.length
  }
})

const filteredRecords = computed(() => {
  const records = recordType.value === 'exam' ? examRecords.value : practiceRecords.value
  return records.filter(item => {
    if (!item) return false
    const name = recordType.value === 'exam' ? `考试${item.examId}` : `练习${item.practiceId}`
    if (!name) return false
    return name.toLowerCase().includes(searchQuery.value.toLowerCase())
  })
})

const getTestIcon = (type) => {
  const icons = {
    mock: '📝',
    chapter: '📚',
    daily: '📖'
  }
  return icons[type] || '📌'
}

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const pad = n => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const formatMonth = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const pad = n => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}`
}

const aggregateByMonth = (records) => {
  const monthlyData = {}
  
  records.forEach(record => {
    const month = formatMonth(recordType.value === 'exam' ? record.examTime : record.startTime)
    const score = recordType.value === 'exam' 
      ? record.score 
      : Math.round(record.correctCount / record.questionCount * 100)
    
    if (!monthlyData[month]) {
      monthlyData[month] = {
        total: 0,
        count: 0
      }
    }
    
    monthlyData[month].total += score
    monthlyData[month].count += 1
  })
  
  return Object.entries(monthlyData).map(([month, data]) => ({
    date: month,
    score: Math.round(data.total / data.count)
  }))
}

const fetchExamPapers = async (userId) => {
  try {
    console.log('开始获取考试试卷信息，用户ID:', userId)
    const response = await axios.get(`http://localhost:8080/user-exams/papers/${userId}`)
    console.log('考试试卷接口响应:', response)
    
    if (!response.data) {
      console.warn('考试试卷接口返回数据为空')
      return
    }
    
    examPapers.value = response.data.reduce((acc, paper) => {
      acc[paper.paperId] = paper
      return acc
    }, {})
    console.log('处理后的考试试卷信息:', examPapers.value)
  } catch (error) {
    console.error('获取考试试卷信息失败:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      config: error.config
    })
    ElMessage.error(`获取考试试卷信息失败: ${error.response?.data?.message || error.message}`)
  }
}

const fetchExamRecords = async () => {
  try {
    const userId = userStore.getUserInfo?.userId
    if (!userId) {
      console.error('用户未登录')
      return
    }
    console.log('开始获取考试记录，用户ID:', userId)
    const response = await axios.get(`http://localhost:8080/userexams/byUser/${userId}`)
    console.log('获取到的考试记录:', response.data)
    examRecords.value = response.data
    await fetchExamPapers(userId)
    console.log('考试记录已更新到响应式数据中')
    updateChart()
  } catch (error) {
    console.error('获取考试记录失败:', error)
  }
}

const fetchPracticeRecords = async () => {
  try {
    const userId = userStore.getUserInfo?.userId
    if (!userId) {
      console.error('用户未登录')
      return
    }
    console.log('开始获取练习记录，用户ID:', userId)
    const response = await axios.get(`http://localhost:8080/userPractices/user/${userId}`)
    console.log('获取到的练习记录:', response.data)
    practiceRecords.value = response.data
    updateChart()
  } catch (error) {
    console.error('获取练习记录失败:', error)
  }
}

const initChart = () => {
  console.log('开始初始化图表')
  if (chartRef.value) {
    console.log('找到图表容器元素')
    scoreChart.value = echarts.init(chartRef.value)
    console.log('图表实例创建成功:', scoreChart.value)
    updateChart()
  } else {
    console.error('未找到图表容器元素')
  }
}

const updateChart = () => {
  console.log('开始更新图表')
  if (!scoreChart.value) {
    console.error('图表实例未初始化')
    return
  }

  try {
    const records = recordType.value === 'exam' ? examRecords.value : practiceRecords.value
    console.log('当前记录类型:', recordType.value)
    console.log('获取到的记录数据:', records)

    if (!records || records.length === 0) {
      console.log('没有可用的记录数据')
      return
    }

    let chartData

    if (timeSpan.value === 'day') {
      console.log('按日显示数据')
      const sortedRecords = [...records].sort((a, b) => 
        new Date(recordType.value === 'exam' ? a.createTime : a.startTime) - 
        new Date(recordType.value === 'exam' ? b.createTime : b.startTime)
      )
      console.log('排序后的记录:', sortedRecords)

      chartData = sortedRecords.map(record => {
        const date = formatDate(recordType.value === 'exam' ? record.createTime : record.startTime)
        const score = recordType.value === 'exam' 
          ? Math.round(record.userScore / record.totalScore * 100)
          : Math.round(record.correctCount / record.questionCount * 100)
        console.log('处理数据点:', { date, score, record })
        return { date, score }
      })
    } else {
      console.log('按月显示数据')
      chartData = aggregateByMonth(records)
    }

    console.log('最终的图表数据:', chartData)

    const option = {
      tooltip: {
        trigger: 'item',
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#6b9bd2',
            width: 1,
            type: 'dashed'
          }
        },
        formatter: function(params) {
          console.log('tooltip formatter 被调用:', params)
          const record = records.find(r => {
            const recordDate = formatDate(recordType.value === 'exam' ? r.createTime : r.startTime)
            return recordDate === params.name
          })
          
          console.log('找到的记录:', record)
          
          if (!record) {
            console.log('未找到对应记录')
            return `${params.name}<br/>${params.seriesName}: ${params.value}%`
          }
          
          if (recordType.value === 'exam') {
            const paperName = examPapers.value[record.paperId]?.paperName || `考试${record.examId}`
            return `<div style="font-weight: bold; margin-bottom: 5px;">${params.name}</div>
                    <div style="margin: 3px 0;">试卷名称: ${paperName}</div>
                    <div style="margin: 3px 0;">得分: ${record.userScore}/${record.totalScore}</div>
                    <div style="margin: 3px 0;">得分率: ${params.value}%</div>
                    <div style="margin: 3px 0;">用时: ${Math.floor(record.duration / 60)}分钟</div>`
          } else {
            const practiceName = getPracticeName(record)
            return `<div style="font-weight: bold; margin-bottom: 5px;">${params.name}</div>
                    <div style="margin: 3px 0;">练习名称: ${practiceName}</div>
                    <div style="margin: 3px 0;">正确题数: ${record.correctCount}/${record.questionCount}</div>
                    <div style="margin: 3px 0;">正确率: ${params.value}%</div>
                    <div style="margin: 3px 0;">用时: ${Math.floor(record.duration / 60)}分钟</div>`
          }
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#6b9bd2',
        borderWidth: 1,
        textStyle: {
          color: '#4a6fa5',
          fontSize: 13
        },
        padding: [10, 15],
        extraCssText: 'box-shadow: 0 0 8px rgba(107, 155, 210, 0.2);',
        showContent: true,
        alwaysShowContent: false,
        triggerOn: 'mousemove',
        enterable: true,
        confine: true
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.map(item => item.date),
        axisLine: {
          lineStyle: {
            color: '#4a6fa5'
          }
        },
        axisLabel: {
          rotate: timeSpan.value === 'day' ? 45 : 0,
          color: '#4a6fa5'
        }
      },
      yAxis: {
        type: 'value',
        name: '分数',
        min: 0,
        max: 100,
        axisLine: {
          lineStyle: {
            color: '#4a6fa5'
          }
        },
        axisLabel: {
          color: '#4a6fa5'
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(74, 111, 165, 0.1)'
          }
        }
      },
      series: [
        {
          name: recordType.value === 'exam' ? '考试成绩' : '练习成绩',
          type: 'line',
          smooth: true,
          data: chartData.map(item => item.score),
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            color: '#6b9bd2',
            width: 3
          },
          itemStyle: {
            color: '#6b9bd2',
            borderWidth: 2,
            borderColor: '#fff'
          },
          emphasis: {
            scale: true,
            focus: 'series',
            itemStyle: {
              shadowColor: 'rgba(107, 155, 210, 0.5)',
              shadowBlur: 10
            }
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(107, 155, 210, 0.3)' },
              { offset: 1, color: 'rgba(107, 155, 210, 0.05)' }
            ])
          }
        }
      ]
    }

    console.log('设置图表配置:', option)
    scoreChart.value.setOption(option)
    console.log('图表配置设置完成')
  } catch (error) {
    console.error('更新图表时发生错误:', error)
  }
}

const fetchCourses = async () => {
  try {
    const response = await axios.get('http://localhost:8080/Courses/all')
    courseMap.value = response.data.reduce((acc, course) => {
      acc[course.courseId] = course.courseName
      return acc
    }, {})
    console.log('获取到的课程信息:', courseMap.value)
  } catch (error) {
    console.error('获取课程信息失败:', error)
  }
}

const getPracticeName = (record) => {
  const courseName = courseMap.value[record.courseId] || '未知课程'
  return `${courseName}-练习${record.practiceId}`
}

watch([recordType, timeSpan], () => {
  if (recordType.value === 'exam') {
    fetchExamRecords()
  } else {
    fetchPracticeRecords()
  }
})

onMounted(() => {
  console.log('组件挂载')
  nextTick(() => {
    console.log('DOM更新完成，准备初始化图表')
    initChart()
  })
  fetchCourses()
  fetchExamRecords()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (scoreChart.value) {
    scoreChart.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (scoreChart.value) {
    scoreChart.value.resize()
  }
}
</script>

<style scoped>
.test-record-container {
  padding: 20px; /* 恢复水平内边距 */
  max-width: 1200px; /* 恢复最大宽度 */
  margin: 0 auto; /* 水平居中 */
  margin-top: 0 !important; /* 保留外部容器与顶部菜单衔接 */
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 恢复 ElCard 默认的 body 内边距 */
:deep(.el-card__body) {
  padding: 20px !important; /* 恢复 ElCard 默认的内边距 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 24px; /* 恢复水平内边距 */
}

.page-header h2 {
  color: #4a6fa5;
  font-size: 1.5rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.record-type-switch {
  margin-right: 16px;
}

.search-input {
  width: 240px;
}

.record-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 24px;
}

.record-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  color: #4a6fa5;
  font-size: 1.1rem;
  margin: 0;
}

.stats-card,
.chart-card,
.list-card {
  grid-column: span 1;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  text-align: center;
}

.stat-item {
  padding: 20px;
  background: rgba(107, 155, 210, 0.05);
  border-radius: 12px;
}

.stat-value {
  font-size: 2rem;
  font-weight: 600;
  color: #4a6fa5;
  margin-bottom: 8px;
}

.stat-label {
  color: #6b8bb0;
  font-size: 0.9rem;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.test-name {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4a6fa5;
}

.test-icon {
  font-size: 16px;
}

.score {
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 4px;
}

.score-excellent {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.score-good {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.score-pass {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.score-fail {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

:deep(.el-table) {
  --el-table-border-color: rgba(107, 155, 210, 0.1);
  --el-table-header-bg-color: rgba(107, 155, 210, 0.1);
}

:deep(.el-table th) {
  font-weight: 600;
  color: #4a6fa5;
}

:deep(.el-table td) {
  color: #5a7ba8;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #6b9bd2, #8bb6e8);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a8bc1, #7aa5d7);
  transform: translateY(-1px);
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 12px rgba(107, 155, 210, 0.1);
}

:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.9);
}

@media (max-width: 1200px) {
  .record-grid {
    grid-template-columns: 1fr;
  }

  .stats-card,
  .chart-card {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }

  .stats-content {
    grid-template-columns: 1fr;
  }
}
</style>
